﻿﻿/**
 * Net8.Identity 认证中心 - 自定义JavaScript
 * 提供增强的用户交互体验
 */

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeAnimations();
    initializeFormEnhancements();
    initializeTooltips();
    initializeKeyboardShortcuts();
});

/**
 * 初始化动画效果
 */
function initializeAnimations() {
    // 为卡片添加进入动画
    const cards = document.querySelectorAll('.card-modern, .feature-card');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        
        setTimeout(() => {
            card.style.transition = 'all 0.6s ease-out';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });

    // 按钮悬停效果增强
    const buttons = document.querySelectorAll('.btn-modern');
    buttons.forEach(btn => {
        btn.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-2px)';
        });
        
        btn.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
}

/**
 * 表单增强功能
 */
function initializeFormEnhancements() {
    // 输入框聚焦效果
    const inputs = document.querySelectorAll('.form-control-modern');
    inputs.forEach(input => {
        input.addEventListener('focus', function() {
            const inputGroup = this.closest('.input-group-modern');
            if (inputGroup) {
                inputGroup.classList.add('focused');
            }
        });
        
        input.addEventListener('blur', function() {
            const inputGroup = this.closest('.input-group-modern');
            if (inputGroup) {
                inputGroup.classList.remove('focused');
            }
        });
        
        // 输入验证
        input.addEventListener('input', function() {
            validateInput(this);
        });
    });

    // 表单提交增强
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            if (!validateForm(this)) {
                e.preventDefault();
                return false;
            }
            
            // 添加提交动画
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn && !submitBtn.disabled) {
                addSubmitAnimation(submitBtn);
            }
        });
    });
}

/**
 * 输入验证
 */
function validateInput(input) {
    const value = input.value.trim();
    const isRequired = input.hasAttribute('required');
    const inputGroup = input.closest('.input-group-modern') || input.parentElement;
    
    // 移除之前的验证状态
    input.classList.remove('is-valid', 'is-invalid');
    
    if (isRequired && !value) {
        input.classList.add('is-invalid');
        showValidationMessage(input, '此字段为必填项');
        return false;
    }
    
    // 密码强度验证
    if (input.type === 'password' && input.name === 'password') {
        if (value.length < 6) {
            input.classList.add('is-invalid');
            showValidationMessage(input, '密码长度至少6位');
            return false;
        }
    }
    
    if (value) {
        input.classList.add('is-valid');
        hideValidationMessage(input);
    }
    
    return true;
}

/**
 * 表单验证
 */
function validateForm(form) {
    const inputs = form.querySelectorAll('.form-control-modern[required]');
    let isValid = true;
    
    inputs.forEach(input => {
        if (!validateInput(input)) {
            isValid = false;
        }
    });
    
    return isValid;
}

/**
 * 显示验证消息
 */
function showValidationMessage(input, message) {
    hideValidationMessage(input);
    
    const feedback = document.createElement('div');
    feedback.className = 'invalid-feedback d-block';
    feedback.style.fontSize = '0.875rem';
    feedback.style.color = 'var(--danger-color)';
    feedback.innerHTML = `<i class="bi bi-exclamation-circle me-1"></i>${message}`;
    
    const inputGroup = input.closest('.input-group-modern') || input.parentElement;
    inputGroup.appendChild(feedback);
}

/**
 * 隐藏验证消息
 */
function hideValidationMessage(input) {
    const inputGroup = input.closest('.input-group-modern') || input.parentElement;
    const feedback = inputGroup.querySelector('.invalid-feedback');
    if (feedback) {
        feedback.remove();
    }
}

/**
 * 提交动画
 */
function addSubmitAnimation(button) {
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>处理中...';
    button.disabled = true;
    
    // 如果3秒后仍未完成，恢复按钮状态
    setTimeout(() => {
        if (button.disabled) {
            button.innerHTML = originalText;
            button.disabled = false;
        }
    }, 3000);
}

/**
 * 初始化工具提示
 */
function initializeTooltips() {
    // 为带有title属性的元素添加现代化tooltip
    const elements = document.querySelectorAll('[title]');
    elements.forEach(element => {
        element.addEventListener('mouseenter', function(e) {
            showTooltip(e.target, e.target.getAttribute('title'));
        });
        
        element.addEventListener('mouseleave', function() {
            hideTooltip();
        });
    });
}

/**
 * 显示工具提示
 */
function showTooltip(element, text) {
    const tooltip = document.createElement('div');
    tooltip.className = 'custom-tooltip';
    tooltip.textContent = text;
    tooltip.style.cssText = `
        position: absolute;
        background: var(--gray-800);
        color: white;
        padding: 0.5rem 0.75rem;
        border-radius: var(--border-radius);
        font-size: 0.875rem;
        z-index: 1050;
        white-space: nowrap;
        box-shadow: var(--shadow-lg);
    `;
    
    document.body.appendChild(tooltip);
    
    const rect = element.getBoundingClientRect();
    tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
    tooltip.style.top = rect.top - tooltip.offsetHeight - 5 + 'px';
}

/**
 * 隐藏工具提示
 */
function hideTooltip() {
    const tooltip = document.querySelector('.custom-tooltip');
    if (tooltip) {
        tooltip.remove();
    }
}

/**
 * 初始化键盘快捷键
 */
function initializeKeyboardShortcuts() {
    document.addEventListener('keydown', function(e) {
        // Ctrl + Enter 提交表单
        if (e.ctrlKey && e.key === 'Enter') {
            const form = document.querySelector('form');
            if (form) {
                form.submit();
            }
        }
        
        // ESC 键关闭模态框或返回
        if (e.key === 'Escape') {
            const modal = document.querySelector('.modal.show');
            if (modal) {
                // 关闭模态框逻辑
            } else if (window.history.length > 1) {
                // 如果不在首页，返回上一页
                if (window.location.pathname !== '/') {
                    window.history.back();
                }
            }
        }
    });
}

/**
 * 通用工具函数
 */
const Utils = {
    /**
     * 防抖函数
     */
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    /**
     * 节流函数
     */
    throttle: function(func, limit) {
        let lastFunc;
        let lastRan;
        return function(...args) {
            if (!lastRan) {
                func(...args);
                lastRan = Date.now();
            } else {
                clearTimeout(lastFunc);
                lastFunc = setTimeout(() => {
                    if ((Date.now() - lastRan) >= limit) {
                        func(...args);
                        lastRan = Date.now();
                    }
                }, limit - (Date.now() - lastRan));
            }
        };
    },
    
    /**
     * 显示通知
     */
    showNotification: function(message, type = 'info', duration = 3000) {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-modern position-fixed`;
        notification.style.cssText = `
            top: 20px;
            right: 20px;
            z-index: 1060;
            min-width: 300px;
            animation: slideInRight 0.3s ease-out;
        `;
        notification.innerHTML = `
            <i class="bi bi-info-circle me-2"></i>${message}
            <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
        `;
        
        document.body.appendChild(notification);
        
        // 自动移除
        setTimeout(() => {
            if (notification.parentElement) {
                notification.style.animation = 'slideOutRight 0.3s ease-in';
                setTimeout(() => notification.remove(), 300);
            }
        }, duration);
    }
};

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOutRight {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
    
    .form-control-modern.is-valid {
        border-color: var(--success-color);
        box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
    }
    
    .form-control-modern.is-invalid {
        border-color: var(--danger-color);
        box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
    }
`;
document.head.appendChild(style);

// 全局暴露Utils对象
window.IdentityUtils = Utils;